package fct.mpc.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class StatManager {

	// Database fields
	private SQLiteDatabase database;
	private DatabaseHelper dbHelper;
	public static String[] allColumns = { 
									DatabaseHelper.STATS_COLUMN_GAMES,
									DatabaseHelper.STATS_COLUMN_BATTLES,
									DatabaseHelper.STATS_COLUMN_SNIPES,
									DatabaseHelper.STATS_COLUMN_WINS };

	protected String user;
	protected int games_played;
	protected int snipes_hunted;
	protected int battles_fought;
	protected int battles_won;
		
	public StatManager(Context context) {
		this.dbHelper = new DatabaseHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}
	
	public int getGames_played() {
		return games_played;
	}
	public void increaseGames_played() {
		this.games_played++;
	}
	public int getSnipes_hunted() {
		return snipes_hunted;
	}
	public void increaseSnipes_hunted() {
		this.snipes_hunted++;
	}
	public int getBattles_fought() {
		return battles_fought;
	}
	public void increaseBattles_fought() {
		this.battles_fought++;
	}
	public int getBattles_won() {
		return battles_won;
	}
	public void increaseBattles_won() {
		this.battles_won++;
	}
	
	@Override
	public String toString() {
		return "["+user+","+
					games_played+","+
					battles_fought+","+
					snipes_hunted+","+
					battles_won+"]";
	}
	
	public void loadStats() {

		Cursor cursor = database.query(DatabaseHelper.STATS_TABLE_NAME,
				allColumns, null, null, null, null, null);

		cursor.moveToFirst();
		buildStat( cursor );
	
		cursor.close();
	}
	
	public List<Map<String, String>> getStatMapping() {
		ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
		list.add( putData( "Games Played", this.games_played) );
		list.add( putData( "Snipe Hunted", this.snipes_hunted) );
		list.add( putData( "Battles Fought", this.battles_fought) );
		list.add( putData( "Battles Won", this.battles_won) );
		
		return list;
	}
		
	private HashMap<String, String> putData(String key, int value) {
		HashMap<String, String> item = new HashMap<String, String>();
		item.put( "key", key);
		item.put( "value", ""+value);
		return item;
	}
	
	private void buildStat(Cursor c) {
		this.user = c.getString( 0 );
		this.games_played = c.getInt(1);
		this.snipes_hunted = c.getInt(2);
		this.battles_fought = c.getInt(3);
		this.battles_won = c.getInt(4);
	}
	
}
